package com.smasher.print.core;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

public class PrintFactory {

    private static final List<PrintPlugin> plugins = new ArrayList<>();

    static {
        // 使用ServiceLoader自动加载所有插件
        ServiceLoader<PrintPlugin> loader = ServiceLoader.load(PrintPlugin.class);
        for (PrintPlugin plugin : loader) {
            if (plugin.isAvailable()) {
                plugins.add(plugin);
            }
        }
    }

    public static PrintHelper createPrintHelper(Context context) {
        PrintHelper helper = new PrintHelper();
        if (!plugins.isEmpty()) {
            // 默认使用第一个可用插件
            PrintDelegate delegate = plugins.get(0).createPrintDelegate(context);
            helper.setPrintDelegate(delegate);
        }
        return helper;
    }

    public static PrintHelper createPrintHelper(Context context, String pluginId) {
        PrintHelper helper = new PrintHelper();
        for (PrintPlugin plugin : plugins) {
            if (plugin.getPluginId().equals(pluginId) && plugin.isAvailable()) {
                PrintDelegate delegate = plugin.createPrintDelegate(context);
                helper.setPrintDelegate(delegate);
                return helper;
            }
        }
        throw new IllegalArgumentException("Plugin not found or not available: " + pluginId);
    }

    public static List<PrintPlugin> getAvailablePlugins() {
        return new ArrayList<>(plugins);
    }
}
